<template>
    <div class="white-box">
        <div>
            <el-button
                v-hasPermi="['enttp:user:export']"
                class="table-mb"
                type="primary"
                @click="state.dialogVisible = true"
                >导出会员信息</el-button
            >
        </div>

        <div class="task-one">
            <div class="task-one__item">
                <span class="task-one__label">会员昵称：</span>
                <el-input
                    placeholder="请输入会员昵称"
                    v-model.trim="state.nickName"
                    max-length="20"
                    clearable
                    @keyup.enter.native="handleSearch"
                ></el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">会员手机：</span>
                <el-input
                    placeholder="请输入手机号码"
                    v-model.trim="state.phone"
                    max-length="11"
                    clearable
                    @keyup.enter.native="handleSearch"
                ></el-input>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">会员性别：</span>
                <el-select v-model="state.sex" placeholder="选择性别" clearable>
                    <el-option
                        v-for="item in state.sexList"
                        :key="item.memberKey"
                        :label="item.memberName"
                        :value="item.memberKey"
                    />
                </el-select>
            </div>
            <div class="task-one__item">
                <span class="task-one__label">会员状态：</span>
                <el-select
                    v-model="state.status"
                    placeholder="选择状态"
                    clearable
                >
                    <el-option
                        v-for="item in state.statusList"
                        :key="item.memberKey"
                        :label="item.memberName"
                        :value="item.memberKey"
                    />
                </el-select>
            </div>
            <div class="task-one__btn clearfix">
                <el-button
                    type="primary"
                    :loading="loading"
                    icon="Search"
                    @click="handleSearch"
                    >搜索</el-button
                >
            </div>
        </div>

        <el-table
            class="table-mb"
            v-loading="loading"
            :data="arr_data"
            row-key="sid"
            :header-cell-style="{
                background: '#F5F7FA',
                textAlign: 'center',
            }"
            :cell-style="
                ({ column }) => {
                    return {
                        textAlign:
                            column.className === 'operation-nav'
                                ? 'left'
                                : 'center',
                        paddingLeft:
                            column.className === 'operation-nav' ? '25px' : '0',
                    };
                }
            "
            border
            element-loading-background="rgba(255, 255, 255, 0.6)"
            @selection-change="selectionChange"
            @sort-change="sortChange"
        >
            <el-table-column
                prop="nickName"
                label="昵称"
                min-width="150"
                fixed="left"
                :show-overflow-tooltip="{
                    'popper-class': 'max-w-800',
                }"
            >
            </el-table-column>
            <el-table-column label="头像" min-width="150">
                <template #default="{ row }"
                    ><Image :src="row.avatar"
                /></template>
            </el-table-column>
            <el-table-column
                prop="phone"
                label="手机号"
                min-width="120"
            ></el-table-column>
            <el-table-column
                prop="status"
                label="状态"
                min-width="100"
                sortable="custom"
            >
                <template #default="{ row }">
                    {{ dictStore.getDictMemberName("data_status", row.status) }}
                </template>
            </el-table-column>
            <el-table-column
                prop="created"
                label="创建时间"
                min-width="160"
                sortable="custom"
            ></el-table-column>
            <el-table-column
                label="操作"
                width="280"
                class-name="operation-nav"
                fixed="right"
            >
                <template #default="{ row }">
                    <MoreBtn
                        :buttons="[
                            {
                                props: {
                                    onClick: () => onClickUserInfo(row.sid),
                                    'v-hasPermi': ['enttp:user:query'],
                                },
                                text: '用户详情',
                            },
                            {
                                props: {
                                    onClick: () => changeStatus(row.sid),
                                    'v-hasPermi': ['enttp:user:update'],
                                },
                                text: ['停用', '启用'][row.status],
                                isRender: showBtns(row.roleKeySet),
                            },
                            {
                                props: {
                                    onClick: () => onClickPlaceOrder(row.sid),
                                    'v-hasPermi': ['enttp:order:createByOther'],
                                },
                                text: '代客下单',
                                isRender: showBtns(row.roleKeySet),
                            },
                            {
                                props: {
                                    onClick: () => onClickStoreInfo(row.sid),
                                    'v-hasPermi': ['enttp:store:query'],
                                },
                                text: '商家详情',
                                isRender: row.storeStatus === 1,
                            },
                            {
                                props: {
                                    onClick: () => openCredit(row),
                                    'v-hasPermi': ['enttp:credit:add'],
                                },
                                text: '开通授信',
                                isRender:
                                    showBtns(row.roleKeySet) &&
                                    row.creditStatus !== 1,
                            },
                            {
                                props: {
                                    onClick: () => openMonthly(row),
                                    'v-hasPermi': ['enttp:monthly:add'],
                                },
                                text: '开通记账',
                                isRender:
                                    showBtns(row.roleKeySet) &&
                                    row.monthStatus !== 1,
                            },
                            {
                                props: {
                                    onClick: () =>
                                        onClickResetPassword(row.sid),
                                    'v-hasPermi': ['enttp:user:upd:password'],
                                },
                                text: '重置密码',
                                isRender: showBtns(row.roleKeySet),
                            },
                        ]"
                    />
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            background
            v-model:current-page="page"
            v-model:page-size="pageSize"
            :page-sizes="pageSizeNum"
            :total="totalNums"
            layout="slot, sizes, prev, pager, next, jumper"
        >
            <span class="color-#606266"
                >共&nbsp;{{
                    totalNums >= 100 * pageSize
                        ? `${100 * pageSize}+`
                        : totalNums
                }}&nbsp;条</span
            >
        </el-pagination>
    </div>

    <!-- 导出 -->
    <el-dialog
        v-model="state.dialogVisible"
        title="导出会员信息-筛选"
        width="600"
        top="10vh"
    >
        <el-form
            ref="ruleRef"
            :model="state.ruleForm"
            :rules="state.rules"
            label-width="120px"
        >
            <el-form-item label="会员名" prop="userName">
                <el-input
                    v-model.trim="state.ruleForm.userName"
                    clearable
                    maxlength="20"
                    placeholder="请输入会员名"
                />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
                <el-input
                    v-model.trim="state.ruleForm.phone"
                    clearable
                    maxlength="11"
                    placeholder="请输入手机号"
                />
            </el-form-item>
            <el-form-item label="性别" prop="sex">
                <el-select
                    v-model="state.ruleForm.sex"
                    placeholder="请选择性别"
                    clearable
                >
                    <el-option
                        v-for="item in state.sexList"
                        :key="item.memberKey"
                        :label="item.memberName"
                        :value="item.memberKey"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="导出起始页码" prop="current">
                <el-input-number
                    v-model="state.ruleForm.current"
                    :min="1"
                    :max="100"
                    :precision="0"
                />
            </el-form-item>
            <el-form-item label="每页条数" prop="size">
                <el-input-number
                    v-model="state.ruleForm.size"
                    :min="10"
                    :max="50"
                    :precision="0"
                    :step="10"
                />
            </el-form-item>
            <el-form-item label="排序属性名" prop="sortFieldName">
                <el-select
                    v-model="state.ruleForm.sortFieldName"
                    placeholder="请选择排序属性名"
                    clearable
                >
                    <el-option label="会员名" value="userName" />
                    <el-option label="手机号" value="phone" />
                    <el-option label="创建时间" value="created" />
                    <el-option label="更新时间" value="updated" />
                </el-select>
            </el-form-item>
            <el-form-item label="排序方式" prop="ascended">
                <el-radio-group v-model="state.ruleForm.ascended">
                    <el-radio :value="false">倒序</el-radio>
                    <el-radio :value="true">正序</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select
                    v-model="state.ruleForm.status"
                    placeholder="请选择状态"
                    clearable
                >
                    <el-option
                        v-for="item in state.statusList"
                        :key="item.memberKey"
                        :label="item.memberName"
                        :value="item.memberKey"
                    />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="state.dialogVisible = false">取消</el-button>
                <el-button
                    type="primary"
                    :loading="form_loading"
                    @click="exportUser(ruleRef)"
                >
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>

    <el-drawer v-model="state.showUserInfo" title="用户信息" size="540">
        <template v-if="userInfo">
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">用户名称</el-col>
                <el-col :span="18">{{ userInfo.nickName }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">用户头像</el-col>
                <el-col :span="18"
                    ><Image :size="100" :src="userInfo.avatar"
                /></el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">手机号</el-col>
                <el-col :span="18">{{ userInfo.phone }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">生日</el-col>
                <el-col :span="18">{{ userInfo.birth }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">性别</el-col>
                <el-col :span="18">{{
                    dictStore.getDictMemberName("sex", userInfo.sex)
                }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">角色</el-col>
                <el-col :span="18">{{
                    getRolesName(userInfo.roleKeySet)
                }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">授信状态</el-col>
                <el-col :span="18">{{
                    userInfo.creditStatus === 1 ? "已开通" : "未开通"
                }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">月结状态</el-col>
                <el-col :span="18">{{
                    userInfo.monthStatus === 1 ? "已开通" : "未开通"
                }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">是否是商家员工</el-col>
                <el-col :span="18">{{
                    userInfo.storeStaffStatus === 1 ? "是" : "否"
                }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">备注</el-col>
                <el-col :span="18">{{ userInfo.note }}</el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="6" align="end" class="mb-20">用户状态</el-col>
                <el-col :span="18">{{
                    dictStore.getDictMemberName("data_status", userInfo.status)
                }}</el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="6" align="end" class="mb-20">创建时间</el-col>
                <el-col :span="18">{{ userInfo.created }}</el-col>
            </el-row>
        </template>
    </el-drawer>

    <el-drawer v-model="state.showStoreInfo" title="商家信息" size="540">
        <template v-if="storeInfo">
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">商家名称</el-col>
                <el-col :span="18">{{ storeInfo.storeName }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">纳税识别号</el-col>
                <el-col :span="18">{{ storeInfo.taxNumber }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">开户人</el-col>
                <el-col :span="18">{{ storeInfo.accountName }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">开户账号</el-col>
                <el-col :span="18">{{ storeInfo.accountBankNumber }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">开户行</el-col>
                <el-col :span="18">{{ storeInfo.accountBank }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">对公账户</el-col>
                <el-col :span="18">{{ storeInfo.accountNumber }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">法人姓名</el-col>
                <el-col :span="18">{{ storeInfo.personName }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">法人身份证</el-col>
                <el-col :span="18">{{ storeInfo.personNumber }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">法人手机号</el-col>
                <el-col :span="18">{{ storeInfo.personPhone }}</el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">营业执照</el-col>
                <el-col :span="18">
                    <Image :size="100" :src="storeInfo.businessImgUrl" />
                </el-col>
            </el-row>
            <el-row :gutter="20" class="mb-20">
                <el-col :span="6" align="end">审核状态</el-col>
                <el-col :span="18">{{
                    dictStore.getDictMemberName(
                        "store_approval",
                        storeInfo.approval
                    )
                }}</el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="6" align="end" class="mb-20">商家状态</el-col>
                <el-col :span="18">{{
                    dictStore.getDictMemberName("data_status", storeInfo.status)
                }}</el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="6" align="end" class="mb-20">创建时间</el-col>
                <el-col :span="18">{{ storeInfo.created }}</el-col>
            </el-row>
        </template>
    </el-drawer>
</template>

<script setup>
import { inject, ref, reactive, onMounted, onActivated, toRefs } from "vue";
import { useRouter } from "vue-router";
import OneLoad from "@mixins/one-load";
import MoreBtn from "@/components/MoreBtn.vue";
import { ElMessageBox } from "element-plus";
import Image from "@/components/Image.vue";
import {
    getUsers,
    getUserDetail as getUserDetailApi,
    delUsers,
    exportUser as exportUserApi,
    changeUserStatus,
    changeUserPassword,
} from "@/apis/user/user";
import { getRolesAll } from "@/apis/system/role";
import { getStoreDetailByUserSid } from "@/apis/store/store.js";
import JSEncrypt from "jsencrypt";
import { getEncrypt } from "@/apis/login";
import { useDictStore } from "@stores/dict.js";

const dictStore = useDictStore();
dictStore.getDictMembers("data_status").then((res) => (state.statusList = res));
dictStore.getDictMembers("sex").then((res) => (state.sexList = res));
dictStore.getDictMembers("store_approval");

const router = useRouter();
const $message = inject("$message");

const form_loading = ref(false);
const ruleRef = ref(null);
const validPhone = (rule, value, callback) => {
    let reg = /^1[23456789]\d{9}$/;
    if (value.length && !reg.test(value)) {
        callback(new Error("请输入正确的11位手机号码"));
    } else {
        callback();
    }
};
const state = reactive({
    statusList: [],
    sexList: [],
    ascended: false,
    orgSid: null,
    sex: null,
    nickName: null,
    phone: null,
    sortFieldName: null,
    status: null,
    dialogVisible: false,
    ruleForm: {
        userName: null,
        phone: null,
        orgSid: null,
        status: null,
        sex: null,
        current: 1,
        size: 10,
        sortFieldName: "created",
        ascended: false,
    },
    rules: {
        phone: [{ validator: validPhone, trigger: "blur" }],
    },
    sidList: [],
    showStoreInfo: false,
    storeInfo: null,
    pub_keys: null,
    showUserInfo: false,
    userInfo: null,
    roleOptions: [],
});

const { storeInfo, userInfo } = toRefs(state);

onMounted(() => {
    getRoleOptions();
});

onActivated(() => {
    pubParams(getList);
});

/**
 * minxin列表加载
 */
const {
    loading,
    arr_data,
    pubRefreshParams,
    getdata,
    page,
    pageSizeNum,
    pageSize,
    totalNums,
    pubParams,
    openPaging,
} = OneLoad();
const { loading: __loading } = OneLoad();

openPaging(getList);

function getList() {
    getdata(
        getUsers({
            current: page.value,
            size: pageSize.value,
            ascended: state.ascended,
            orgSid: state.orgSid,
            phone: state.phone,
            sortFieldName: state.sortFieldName,
            sex: state.sex,
            status: state.status,
            nickName: state.nickName,
        })
    );
}

// 搜索
const handleSearch = () => {
    pubRefreshParams(getList);
};

// 跳转添加菜单页
const onClickAdd = () => {
    router.push({ name: "UserAdd" });
};

// 排序
const sortChange = (e) => {
    const { property, order } = e.column;
    state.ascended = order === "ascending";
    state.sortFieldName = order ? property : null;
    pubRefreshParams(getList);
};

const onClickPlaceOrder = (sid) => {
    sid &&
        router.push({
            name: "ProxyCustomerPlaceOrder",
            query: {
                sid,
                ownerType: 1,
            },
        });
};

// 跳转修改页
const onClickEdit = (sid) => {
    sid &&
        router.push({
            name: "UserEdit",
            query: {
                sid,
            },
        });
};

const changeStatus = async (sid) => {
    const res = await changeUserStatus({ sid });
    if (res.data.code == 200) {
        $message({ message: "操作成功", type: "success" });
        pubParams(getList);
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 选择项改变时
const selectionChange = (e) => {
    state.sidList = e.map((item) => item.sid);
};

// 删除
const onClickDel = async (sid) => {
    if (sid) {
        state.sidList = [sid];
    }
    if (!state.sidList.length) {
        return $message({ message: "请先勾选要删除的数据", type: "warning" });
    }
    await ElMessageBox.confirm("确定删除会员吗？");
    const res = await delUsers({ sidList: state.sidList });
    if (res.data.code == 200) {
        $message({ message: "删除成功", type: "success" });
        pubParams(getList);
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const exportUser = async () => {
    const res = await exportUserApi(state.ruleForm);
    if (res.data.code == 200) {
        $message({
            message: "导出成功，请前往文件管理菜单下载",
            type: "success",
        });
        state.dialogVisible = false;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 查看商家信息
const onClickStoreInfo = (sid) => {
    state.showStoreInfo = true;
    state.storeInfo = null;
    getDetail(sid);
};

const getDetail = async (sid) => {
    const res = await getStoreDetailByUserSid({ sid });
    if (res.data.code == 200) {
        state.storeInfo = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 查看用户信息
const onClickUserInfo = (sid) => {
    state.showUserInfo = true;
    state.userInfo = null;
    getUserDetail(sid);
};

const getUserDetail = async (sid) => {
    const res = await getUserDetailApi({ sid });
    if (res.data.code == 200) {
        state.userInfo = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 开通授信
const openCredit = ({ sid, nickName, phone }) => {
    sid &&
        router.push({
            name: "CreditAdd",
            query: {
                userSid: sid,
                nickName: encodeURIComponent(nickName),
                phone,
            },
        });
};

// 开通记账月结
const openMonthly = ({ sid, nickName, phone }) => {
    sid &&
        router.push({
            name: "MonthlyAdd",
            query: {
                userSid: sid,
                nickName: encodeURIComponent(nickName),
                phone,
            },
        });
};

const getRoleOptions = async () => {
    const res = await getRolesAll();
    if (res.data.code == 200) {
        state.roleOptions = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const getRolesName = (roleKeySet = []) => {
    return roleKeySet
        .reduce((pre, cur) => {
            const role = state.roleOptions.find((item) => item.roleKey === cur);
            if (role) pre.push(role.roleName);
            return pre;
        }, [])
        .toString();
};

const getKey = async () => {
    const res = await getEncrypt();
    if (res.data.code == 200) {
        state.pub_keys = res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

const onClickResetPassword = (sid) => {
    ElMessageBox.prompt("请输入新密码", "重置密码", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputType: "password",
        inputValidator: (value) => {
            if (value?.trim().length) {
                const regu = /^[a-zA-Z0-9!@#$%^&*_]{6,20}$/;
                if (!regu.test(value)) {
                    return "密码只能由6-20位数字字母以及 !@#$%^&*_ 组成";
                } else {
                    return true;
                }
            } else {
                return "请输入新密码";
            }
        },
        inputPlaceholder: "请输入新密码",
    }).then(async ({ value }) => {
        await getKey();
        const encryptor = new JSEncrypt(); // 创建加密对象实例
        encryptor.setPublicKey(state.pub_keys); // 设置公钥
        const password = encryptor.encrypt(value); // 对内容进行加密
        const res = await changeUserPassword({
            sid,
            password,
        });
        if (res.data.code === 200) {
            $message({ message: "修改成功", type: "success" });
        } else {
            $message({ message: res.data.msg, type: "error" });
        }
    });
};

// 角色为 ent_admin 或 ent_owner 时只能修改密码, sys_rpc_user 不能进行任何操作
const showBtns = (roleKeySet = []) => {
    return (
        !roleKeySet.includes("ent_admin") &&
        !roleKeySet.includes("sys_rpc_user") &&
        !roleKeySet.includes("ent_owner")
    );
};
</script>
